<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html lang="zh">
<head>
    <title>物资出借记录</title>
    <jsp:include page="/WEB-INF/view/commons/css.jsp" />
</head>
<body >
<div id="main-container" class="container-fluid">
    <form  action="appMaterialsLend/${action eq "create" ?"save":"update"}" name="inputForm" id="inputForm" method="post" class="form-horizontal">
    <input name="id" id="id" value="${entity.id}" type="hidden" />
    <input name="lendCode" id="lendCode" value="${barCode}" type="hidden" />
    <input name="orgName" id="orgName" value="${entity.orgName}" type="hidden" />
    <input name="grantOrgName" id="grantOrgName" value="${grantOrgName}" type="hidden" />
    <input name="grantOrgId" id="grantOrgId" value="${grantOrgId}" type="hidden" />
    
    <c:if test="${action == 'create'}">
        <div class="infobder">
            <div class="table-header">物资出借登记步骤</div>
            <table class="table table-striped table-bordered table-hover">
                <thead>
                    <tr><th>序号</th><th>操作步骤</th></tr>
                </thead>
                <tbody>
                    <tr><td class="center">1</td><td>选择来往单位<i class="fa fa-org"></i></td></tr>
                    <tr><td class="center">2</td><td>请点击序号行内物资名称列，在弹出窗口中选择物资进行添加<i class="fa fa-mat"></i></td></tr>
                    <tr><td class="center">3</td><td>点击数量列下对应物资的数量表格， 填写数量<i class="fa fa-in"></i></td></tr>
                    <tr><td class="center">4</td><td>填写经办人姓名<i class="fa fa-agentName"></i></td></tr>
                    <tr><td class="center">5</td><td>保存，完成物资出库登记！</td></tr>
                </tbody>
            </table>
        </div>
    </c:if>
        
        <div class="mt20">
            <div class="row form-group">
                <div class="col-sm-12">
                    <input class="form-control inline" type="text" value="${entity.lendTitle}" name="lendTitle" placeholder="请填写主题">
                </div>
            </div>
            <div class="info-title">
                <h2>物资出借登记表</h2>
                <img src="data:image/png;base64,${barCodeImg}">
            </div>
            <div class="row mt20">
                <div class="col-sm-8" style="padding-top: 7px">${barCode}</div>
                <div class="form-group col-sm-4" style="padding-right: 0">
                    <label class="control-label col-sm-4">来往单位</label>
                    <div class="col-sm-8" style="padding-right: 0">
                        <select id="orgSelect" class="selectpicker form-control" name="orgId">
                        	<option value="" selected>--请选择--</option>
                        	<c:forEach var="obj" items="${orgList}" varStatus="i">
                        		<option value="${obj.id}">${obj.orgName}</option>
                        	</c:forEach>
                        </select>
                    </div>

                </div>
            </div>
            <table id="table_data" class="table table-striped table-bordered table-hover">
                <thead id="mainthead">
                <tr>
                    <th style="width: 30px;">序号</th>
                    <th style="width: 150px;">物资名称</th>
                    <th style="width: 50px;">规格</th>
                    <th style="width: 50px;">单位</th>
                    <th style="width: 50px;">数量</th>
                    <th style="width: 150px;">备注</th>
                    <th style="width: 150px;">操作</th>
                </tr>
                </thead>
                <tbody id="maintbody">
                <c:choose>
                    <c:when test="${appLendDetailList!= null && fn:length(appLendDetailList)>0}">
                        <c:forEach var="each" varStatus="vs" items="${appLendDetailList}">
                            <tr>
                                <td class='center'>${vs.index+1}</td>
                                <td class='center' onclick="showDialog();" >
                                    <span id="materialsName${vs.index}s">${each.materialsName}</span>
                                    <input type="hidden" id="materialsId${vs.index}" name="itemEntity[${vs.index}].materialsId" value="${each.materialsId}"/>
                                    <input type="hidden" id="materialsName${vs.index}" name="itemEntity[${vs.index}].materialsName" value="${each.materialsName}"/>
                                    <input type="hidden" name="isActive" value="1">
                                    <input type="hidden" name="detailId" value="${each.id}">
                                    <input type="hidden" id="id${vs.index}" name="itemEntity[${vs.index}].id" value="${each.id}">
                                </td>
                                <td class='center'>
                                    <span id="specification${vs.index}s">${each.specification}</span>
                                    <input type="hidden"  id="specification${vs.index}" name="itemEntity[${vs.index}].specification" value="${each.specification}"/>
                                </td>
                                <td class='center'>
                                    <span id="unit${vs.index}s">${each.unit}</span>
                                    <input type="hidden"  id="unit${vs.index}" name="itemEntity[${vs.index}].unit" value="${each.unit}"/>
                                </td>
                                <td class='center'>
                                    <input class="input-num" type="number" id="lendNum${vs.index}" name="itemEntity[${vs.index}].lendNum" value="${each.lendNum}" placeholder="出库数量" min='1' max='${each.lendNum + each.enableStockNum}' required/>
                                </td>
                                <td class='center'>
                                    <input type="text" id="remark${vs.index}" name="itemEntity[${vs.index}].remark" value="${each.remark}" placeholder="备注信息" data-rule-maxlength="50"/>
                                </td>
                                <td class='center edit'>
                                    <i class="fa fa-times-circle" onclick="handlerDelete(this, this.parentElement.parentElement.rowIndex)"></i>
                                </td>
                            </tr>
                        </c:forEach>
                    </c:when>
                    <c:otherwise>
                            <c:forEach var="each" begin="0" end="0" varStatus="vs">
                            <tr id="trs${vs.index}">
                                <td class='center'>${vs.index+1}</td>
                                <td class='center' onclick="showDialog();" >
                                    <span id="materialsName${vs.index}s"></span>
                                    <input type="hidden" name="itemEntity[${vs.index}].materialsId" value=""/>
                                    <input type="hidden" name="itemEntity[${vs.index}].materialsName" value=""/>
                                </td>
                                <td class='center'>
                                    <span id="specification${vs.index}s"></span>
                                    <input type="hidden" name="itemEntity[${vs.index}].specification" value=""/>
                                </td>
                                <td class='center'>
                                    <span id="unitStr${vs.index}s"></span>
                                    <input type="hidden" name="itemEntity[${vs.index}].unit" value=""/>
                                </td>
                                <td class='center'>
                                    <input type="number" name="itemEntity[${vs.index}].lendNum" value="" placeholder="借出数量" required/>
                                </td>
                                <td class='center'>
                                    <input type="text" name="itemEntity[${vs.index}].remark" value="" placeholder="备注信息" data-rule-maxlength="50"/>
                                </td>
                                <td class='center edit'>
                                    <i class="fa fa-times-circle" onclick="handlerDelete(this, this.parentElement.parentElement.rowIndex)"></i>
                                </td>
                            </tr>
                            </c:forEach>
                    </c:otherwise>
                </c:choose>
                </tbody>
            </table>
            <div class="row">
                <div class="col-sm-4">发放单位：${grantOrgName} ${user.name}</div>
                <div class="col-sm-4">出借时间：${entity.lendTimeStr}</div>
                <div class="col-sm-4 form-group">
                    <div class="control-label col-sm-4">经办人：</div>
                    <div class="col-sm-8">
                        <input type="text" name="agentName" class="form-control" value="${entity.agentName}">
                    </div>
                </div>
            </div>
            <div class="row">
                <div class="col-sm-8 form-group">
                    <div class="col-sm-2" style="width: 10%">备注：</div>
                    <div class="col-sm-8">
                        <input type="text" class="form-control" name="remark" value="${entity.remark}">
                    </div>
                </div>
            </div>
        </div>

    <div class="form-group">
        <div class="col-sm-offset-4 col-sm-4">
        	<button type="button" class="btn btn-sm btn-primary" onclick="saveAndPrint();"><i class="fa fa-floppy-o"></i> 保存并打印</button>
            <button type="button" class="btn btn-sm btn-primary" onclick="savenAndSign();"><i class="fa fa-floppy-o"></i> 保存并签署</button>
            <button type="button" class="btn btn-sm btn-primary" onclick="save();"><i class="fa"></i> 保存</button>
        </div>
    </div>
    </form>
</div><!--/#main-container-->

<!-- script start -->
<jsp:include page="/WEB-INF/view/commons/js.jsp" />
<script type="text/javascript">
	var outDetailArr = new Array();
	var returnArr = new Array();
    $(document).ready(function(e) {
       	var options = {
   			debug:true,
            rules:{
                lendCode : { required : true, maxlength : 50 },
                lendTitle : { maxlength : 100 },
                orgName : { required : true, maxlength : 100 },
                orgId : { required : true, digits : true  },
                grantOrgName : { required : true, maxlength : 50 },
                grantOrgId : { required : true, digits : true },
                agentName : { required : true, maxlength : 50, isText: true }
            }
        };
        
        $("#inputForm").validate(options);
        
        $("#orgSelect").change(function(i, e){
        	if ($(this).val() == "") {
        		$(".fa-org").removeClass("fa-check");
        	}else{
        		$(".fa-org").addClass("fa-check");
        		var name = $(this).find("option:selected").text();
        		$("#orgName").val(name);
        	}
        });
        
        $("input[name=agentName]").bind('input propertychange', function(){
        	if ($(this).val() == "") {
        		$(".fa-agentName").removeClass("fa-check");
        	}else{
        		$(".fa-agentName").addClass("fa-check");
        	}
        });
        
    });
    // 初始化下拉框的值
    var orgId = "${entity.orgId}";
    $("#orgSelect").val(orgId);







    //定义全局变量储存当前table中的数据
    var curDetails;
    function getTableArr(){
        curDetails = [];
        var trList = $("#maintbody").children("tr");
        for (var i=0;i<trList.length;i++) {
            var tdArr = trList.eq(i).find("td");
            var materialsId = tdArr.eq(1).find('input').eq(0).val();
            var materialsName = tdArr.eq(1).find('input').eq(1).val();
            var isActive = tdArr.eq(1).find('input').eq(2).val(); //是否从库里面删除数据
            var detailId = tdArr.eq(1).find('input').eq(3).val(); //是否从库里面删除数据
            var specification = tdArr.eq(2).find('input').val();
            var unit = tdArr.eq(3).find('input').val();
            var lendNum = tdArr.eq(4).find('input').val();//出库数量
            var placeholder = tdArr.eq(4).find('input').attr('placeholder');
            var remark = tdArr.eq(5).find('input').val();//备注
            curDetails.push({
                "id":materialsId,
                "materialsId": materialsId,
                "materialsName": materialsName,
                "specification": specification,
                "unit" : unit,
                "unitStr" : unit,
                "lendNum": lendNum,
                "enableStockNum":placeholder,
                "remark": remark,
                "isActive": isActive,
                "detailId" : detailId
            });
        }
        return curDetails;
    }


    function showDialog(){
        getTableArr();
        $.extend(true,outDetailArr, curDetails); //深度合并outDetailArr添加填写的出库数量和备注
        returnArr = [];//清空当前变量
        $.each(outDetailArr,function(i,n){ //返回移除后的最终数组
            $.each(curDetails,function(j,s){
                if(n.id == s.id){
                    returnArr.push(n);
                }
            })
        });
    	var layerIndex = layer.open({
            title: "选择出借物资",
            type: 2,
            content: "/bizMaterialsManage/select/",
            area: [800+"px", 570+"px"],
            success:function(layero,index){
                var body = layer.getChildFrame('body',index);
                var iframeWin = window[layero.find('iframe')[0]['name']];
                $.each(returnArr,function(i,n){
                    if(!n.id){
                       var index = $.inArray(n,returnArr);
                        returnArr.splice(index,1);
                    }
                });
                iframeWin.inputDataHandle(returnArr, 1);
            },
            btn: ['确定'],
            yes: function(index, layero){
            	layer.close(index);
            }
        });
    }
    
  	//保存并打印
    function saveAndPrint(){
  		var option = {
			type:'post',
             dataType:'json',
             success:function(data){
                 if(data.success){
                     $('#searchBtn', parent.document).click();
                     layer.open({
                         title: "打印",
                         type: 2,
                         content: "appMaterialsLend/lendPrint/"+data.data,
                         area: ['60%', '90%'],
                         success:function(layero,index){
                         },
                         cancel:function(){
                        	 closeParentIframe();
                         }
                     });
                 }else{
                     layer.alert(data.msg);
                 }
             }
  		}
  		handlerSubmit(option);
    }
  	
  	//保存并签署
  	function savenAndSign(){
  		var option = {
			type:'post',
              dataType:'json',
              success:function(data){
                  if(data.success){
                      $('#searchBtn', parent.document).click();
                      layer.open({
                          title: "待签署",
                          type: 2,
                          content: "appMaterialsLend/lendSign/"+data.data,
                          area: ['60%', '90%'],
                          success:function(layero,index){
                          	
                          },
                          cancel:function(){
                         	 closeParentIframe();
                          }
                      });
                  }else{
                      layer.alert(data.msg);
                  }
              }
  		}
  		handlerSubmit(option);
  	}
  	
  	//保存
  	function save(){
  		var option = {
			type:"post",
              dataType:"json",
              success:function(data){
                  if(data.success){
                      $("#searchBtn", parent.document).click();
                      layer.alert(data.msg,function(){
                          closeIframe();
                      });
                  }else{
                      layer.alert(data.msg);
                  }
              }
  		}
  		handlerSubmit(option);
  	}
  	
  	function handlerSubmit(option){
        if(getTableArr().length == 1 && getTableArr()[0].id==''){
            layer.alert("请选择物资！");
        }else{
            if($("#inputForm").valid()){
                $("#inputForm").ajaxSubmit(option);
            }
        }
  	}
    
  //渲染当前页的表格数据
    function changeSelectedData(msg){
        outDetailArr = msg;
        var tbody = $("#maintbody");
        tbody.html("");
        $.each(msg, function (i,n){
            $(".fa-mat").addClass("fa-check");
            var tr = $("<tr></tr>");
            tr.appendTo(tbody);
            var td = $("<td class='center'>"+(i+1)+"</td>");
            td.appendTo(tr)
            var td = $("<td class='center' onclick='showDialog();'> <span id='materialsName"+i+"s'>"+n.materialsName+"</span><input type='hidden' name='itemEntity["+i+"].materialsId' value='"+n.id+"'/><input type='hidden' name='itemEntity["+i+"].materialsName'value='"+n.materialsName+"'/><input type='hidden' name='isActive' value='"+ (n.isActive ? n.isActive : '') +"'><input type='hidden' name='detailId' value='" + (n.detailId ? n.detailId : '0') + "'></td>");
            td.appendTo(tr)
            var td = $("<td class='center'><span id='specification"+i+"s'>"+n.specification+"</span> <input type='hidden' name='itemEntity["+i+"].specification' value='"+n.specification+"'/></td>");
            td.appendTo(tr)
            var td = $("<td class='center'><span id='unitStr"+i+"s'>"+n.unitStr+"</span><input type='hidden' name='itemEntity["+i+"].unit' value='"+n.unitStr+"'/> </td>");
            td.appendTo(tr)
            var td = $("<td class='center'><input class='input-num' type='number' name='itemEntity["+i+"].lendNum' value='"+ (n.lendNum ? n.lendNum : '') +"' onchange='changefain(this)' placeholder='" + n.enableStockNum + "' min='1' max='" + n.enableStockNum + "' required/></td>");
            td.appendTo(tr)
            var td = $("<td class='center'><input type='text' name='itemEntity["+i+"].remark' value='" + (n.remark ? n.remark : '') + "' placeholder='备注信息' data-rule-isText='true' data-rule-maxlength='50'/> </td>");
            td.appendTo(tr)
            var td = $("<td class='center edit'><i class='fa fa-times-circle' onclick='handlerDelete(this, this.parentElement.parentElement.rowIndex);'></i></td>")
            td.appendTo(tr)
        });
        if(msg.length == 0){
            $(".fa-mat").removeClass("fa-check");
        	var i = 0;
			var tr = $("<tr></tr>");
			var td = $("<td class='center'>"+(i+1)+"</td>");
            td.appendTo(tr)
            var td = $("<td class='center' onclick='showDialog();'> <span id='materialsName"+i+"s'></span><input type='hidden' name='itemEntity["+i+"].materialsId' value=''/><input type='hidden' name='itemEntity["+i+"].materialsName'value=''/></td>");
            td.appendTo(tr)
            var td = $("<td class='center'><span id='specification"+i+"s'></span> <input type='hidden' name='itemEntity["+i+"].specification' value=''/></td>");
            td.appendTo(tr)
            var td = $("<td class='center'><span id='unitStr"+i+"s'></span><input type='hidden' name='itemEntity["+i+"].unit' value=''/> </td>");
            td.appendTo(tr)
            var td = $("<td class='center'><input class='input-num' type='number' name='itemEntity["+i+"].lendNum' value=''  placeholder='出借数量' required/></td>");
            td.appendTo(tr)
            var td = $("<td class='center'><input type='text' name='itemEntity["+i+"].remark' value='' placeholder='备注信息' data-rule-isText='true' data-rule-maxlength='50'/> </td>");
            td.appendTo(tr)
            var td = $("<td class='center edit'><i class='fa fa-times-circle' onclick='handlerDelete(this, this.parentElement.parentElement.rowIndex);'></i></td>")
            td.appendTo(tr)
            tr.appendTo(tbody);
    	}
        $("#mainthead").after(tbody);
    }

    function changefain(arg){
        if(!arg.value){
            $(".fa-in").removeClass("fa-check");
        }else{
            $(".fa-in").addClass("fa-check");
        }
    }

  // 删除行
  function handlerDelete(obj, rowIndex){
	  var tr = $(obj).parent().parent();
	  var tdArr = tr.find("td");
	  var isActive = tdArr.eq(1).find('input').eq(2).val(); //是否从库里面删除数据
	  var id = tdArr.eq(1).find('input').eq(3).val();
      var materialsId = tdArr.eq(1).find('input').eq(0).val(); //materialsId
	  if(isActive == 1){  //删除数据库中的记录
		  layer.confirm("删除后该条物资将彻底从以保存的单据内删除，您确定要删除吗？", function(index) {
	            layer.close(index);
	            $.ajax({
	                url: "appLendDetail/deleteInfo/" + id,
	                type: "DELETE",
	                dataType: "json",
	                success: function (data) {
	                    if(data.success){
                            deleteCurTrRenderTable(obj,materialsId);
	                    }else{
	                        layer.alert(data.msg);
	                    }
	                }
	            });
	        });
	  }else{
          deleteCurTrRenderTable(obj,materialsId);
	  }
  }

    function deleteCurTrRenderTable(obj,materialsId){
        var a = new Object();
        a.id = materialsId;
        removeObjWithArr(outDetailArr, a);
        $(obj).parent().parent().remove();
        //如果是第一行，则新增一行空
        if(!outDetailArr){
            changeSelectedData(outDetailArr);
        }else{
            changeSelectedData(getTableArr());
        }
        if($("#maintbody").find("tr").length == 0 ){
            changeSelectedData([]);
        }
    }
</script>
<!-- script end -->
</body>
</html>
